package com.hnd.springframerwork.beans.factory.support;

import com.hnd.springframerwork.beans.factory.BeanFactory;
import com.hnd.springframerwork.beans.factory.config.BeanDefinition;
import com.hnd.springframerwork.beans.factory.config.BeanPostProcessor;
import com.hnd.springframerwork.beans.factory.config.ConfigurableBeanFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * 定义模板
 */
public abstract class AbstractBeanFactory extends DefaultSingletonBeanRegistry implements ConfigurableBeanFactory {

    private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<>();
    @Override
    public Object getBean(String beanName) {
        return doGetBean(beanName, null);
    }

    @Override
    public Object getBean(String beanName, Object... args) {
        return doGetBean(beanName, args);

       /* Object bean = getSingleton(beanName);

        if (bean != null) {
            return bean;
        }

        BeanDefinition beanDefinition = getBeanDefinition(beanName);

        bean = createBean(beanName, beanDefinition, args);

        addSingleton(beanName, bean);
        return bean;*/
    }

    /**
     * 获取beanDefinition
     *
     * @param beanName
     * @return
     */
    abstract BeanDefinition getBeanDefinition(String beanName);

    /**
     * 创建bean实例(有参)
     *
     * @param beanName
     * @param beanDefinition
     * @return
     */
    abstract Object createBean(String beanName, BeanDefinition beanDefinition, Object... args);

    /**
     * 创建bean实例(无参)
     *
     * @param beanName
     * @param beanDefinition
     * @return
     */
    abstract Object createBean(String beanName, BeanDefinition beanDefinition);

    @Override
    public <T> T getBean(String beanName, Class<T> requireType) {
        return (T) getBean(beanName);
    }

    protected <T> T doGetBean(String name, Object[] args) {
        Object bean = getSingleton(name);
        if (bean != null) {
            return (T) bean;
        }
        BeanDefinition beanDefinition = getBeanDefinition(name);

        return (T) createBean(name, beanDefinition, args);
    }

    @Override
    public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
        beanPostProcessors.remove(beanPostProcessor);
        beanPostProcessors.add(beanPostProcessor);
    }

    public List<BeanPostProcessor> getBeanPostProcessors(){
        return beanPostProcessors;
    };
}
